<style lang="scss">
  @import "../../../utils/base.scss";
</style>
<template>
  <div>
    <!-- 基本信息 -->
    <template id="startegies">


      <!-- 附件 -->
      <template>
        <!-- <component ref="file" :is="'file'" :ifedit="ifedit" :filesList="PfilesList" :Papply="networkInfo"></component> -->
        <component ref="file" :is="'file'" :ifedit="ifedit" :filesList="filesList" v-model="networkInfo.files"></component>
      </template>

    </template>

  </div>
</template>
<script>
  import ajax from "../../../ajax_util"
  import Axios from 'axios'
  import {
    mavonEditor
  } from 'mavon-editor'
  import 'mavon-editor/dist/css/index.css'
  import file from '../settledin/file'
  import excel from "../../../utils/excel";

  export default {
    name: "strategy",
    components: {
      mavonEditor,
      file
    },
    data() {
      return {
        show_detail:true,
        show_oriAddr: false,
        INDEX: "",
        KEY: "",
        TITLE: "",
        startegies: [],
        selection_temp: [],
        template: false,
        countSys: [],
        total_num: 0,

        loading: true,
        data: [],

        page: 1,
        pageSize: 10,
        search_param: '',
        url_id: '0',
        strategyyUrl: this.CONFIG.progress_url + "/net-strategy",

        reqId: "",
        mdvalue: "",
        dataInfoEdit: 0,
        showFileMould: false,
        httpHeader: {
          Authorization: this.$store.state.token
        },
        disabledDate: {
          disabledDate(date) {
            return date && date.valueOf() < Date.now();
          }
        },

        fileUrl: this.CONFIG.file_url,
        readonly: true, //是否只读
        labelWidth: 140,
        bealoonTrue: true,
        file: null,
        loadingStatus: false,
        fileUpLoadAction: "",
        name: "",
        istrue: true,
        networkInfo: this.Papply,
        filesList: this.PfilesList,
      }
    },
    computed: {
      severColumns2() {
        let severColumns2 = []
        severColumns2.push({
          type: 'selection',
          width: 60,
          align: 'center'
        });
        severColumns2.push({
          title: "访问方向 (*必填)",
          align: "center",
          width: 200,
          key: "direction",
          slot: "direction",
        });
        severColumns2.push({
          title: "源地址 (*必填)",
          align: "center",
          width: 240,
          key: "oriAddr",
          // slot: "oriAddr"
        });
        severColumns2.push({
          title: "源地址对应的映射IP (选填)",
          align: "center",
          width: 240,
          key: "oriMapAddr",
          // slot: "oriMapAddr"
        });
        severColumns2.push({
          title: "源端口",
          align: "center",
          width: 120,
          key: "oriPortFrom",
          // children: [
          //     {
          //         title: '从',
          //         align: 'center',
          //         width: 110,
          //         key: "oriPortFrom",
          //         // slot: "oriPortFrom"
          //     },
          //     {
          //         title: '到',
          //         align: 'center',
          //         width: 110,
          //         key: "oriPortTo",
          //         // slot: "oriPortTo"
          //     },
          // ]
        });
        severColumns2.push({
          title: "目的地址 (*必填)",
          align: "center",
          width: 240,
          key: "targetAddr",
          // slot: "targetAddr"
        });
        severColumns2.push({
          title: "目的地址对应的映射IP (选填)",
          align: "center",
          width: 240,
          key: "targetMapAddr",
          // slot: "targetMapAddr"
        });
        severColumns2.push({
          title: "目的端口 (*必填)",
          align: "center",
          width: 130,
          key: "targetPortfrom",
          // children: [
          //     {
          //         title: '从',
          //         align: 'center',
          //         width: 130,
          //         key: "targetPortfrom",
          //         // slot: "targetPortfrom"
          //     },
          //     {
          //         title: '到',
          //         align: 'center',
          //         width: 130,
          //         key: "targetPortTo",
          //         // slot: "targetPortTo"
          //     },
          // ]
        });
        severColumns2.push({
          title: "传输协议 (*必填)",
          align: "center",
          width: 130,
          key: "tcpProtocol",
          slot: "tcpProtocol",
          // children: [
          //     {
          //         title: "TCP",
          //         align: "center",
          //         width: 100,
          //         key: "tcpProtocol",
          //         slot: "tcpProtocol"
          //     },
          //     {
          //         title: 'UDP',
          //         align: 'center',
          //         width: 100,
          //         key: "udpProtocol",
          //         slot: "udpProtocol"
          //     },
          // ]
        });
        severColumns2.push({
          title: "应用层协议 (选填)",
          align: "center",
          width: 130,
          key: "appProtocol",
          // slot: "appProtocol"
        });
        severColumns2.push({
          title: "策略用途 (*必填)",
          align: "center",
          width: 200,
          key: "purpose",
          // slot: "purpose"
        });
        return severColumns2;
      },
    },
    created: function() {
      console.log("------------>", this.severColumns);
      console.log('this.networkInfo', this.networkInfo)
    },
    mounted: function() {
      this.get_all_strategy();
      this.$nextTick(() => {
        this.networkInfo = this.Papply
        if(this.networkInfo.netType == '内网' || this.networkInfo.netType == 'CMNetDCI_vpn'){
          this.show_detail = false
        }
      })
    },

    methods: {
      validateIP(rule, value, callback) {
        if (value != '' && !this.checkIP(this.splitIP(value))) {
          callback(new Error('请正确填写IP'));
        } else if (value == '') {
            callback(new Error('请填写IP'));
        }else{
          callback()
        }
      },
      validateIP2(rule, value, callback) {
        if(this.networkInfo.netType == '内网' || this.networkInfo.netType == 'CMNetDCI_vpn'){
          // if (value != '') {
          //   callback(new Error('无需填写该IP'));
          // } else {
            callback()
          // }
        }else{
          if (value == '') {
            callback(new Error('请填写IP'));
          }else if(!this.checkIP(this.splitIP(value))){
            callback(new Error('请正确填写IP'));
          }else {
            callback()
          }
        }
      },
      selectNumber() {
        const el = document.getElementById("numberfile");
        el.click();
      },
      async importNumber() {
        const el = document.getElementById("numberfile");
        const file = el.files[0];
        var that = this
        var data = await excel.importSheets(file, -1, -1, "", 0);
        console.log("=====importNumber======", data);
        console.log("data.length", data.length);
        if (data.length > 0) {
          this.handlefile(data)
          that.$Notice.success({
            title: '导入成功',
          });
        } else {
          that.$Notice.error({
            title: '导入失败',
          });
        }

        console.log("projectList-------->", data)
        el.value = "";
      },
      handlefile(data) {
        console.log('handlefile--------', data)
        var strategyList = data.find(e => e.sheetName == '策略详情').body
        if (strategyList.length > 0) {
          strategyList.forEach((item, index) => {
            var temp = {
              "appProtocol": "",
              "direction": "",
              "oriAddr": "",
              "oriMapAddr": "",
              "oriPortFrom": "",
              "oriPortTo": "",
              "purpose": "",

              "targetAddr": "",
              "targetMapAddr": "",
              "targetPortTo": "",
              "targetPortfrom": "",
              "tcpProtocol": "",
              "udpProtocol": ""
            }
            // console.log('item',item)
            // console.log('index',index)
            temp.direction = item['访问方向']
            temp.oriAddr = item['源地址']
            temp.oriMapAddr = item['源地址对应的映射IP']
            temp.oriPortFrom = item['源端口']
            temp.targetAddr = item['目的地址']
            temp.targetMapAddr = item['目的地址对应的映射IP']
            temp.targetPortfrom = item['目的端口']
            temp.tcpProtocol = item['传输层协议']
            temp.appProtocol = item['应用层协议']
            temp.purpose = item['策略用途']
            this.networkInfo.startegies.push(temp)
          })
        }
      },

      isValidIP(ip) {
        var reg =
          /^(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$/
        return reg.test(ip);
      },
      splitIP(data) {
        var result = []
        var split_1 = data.split('\n')
        split_1.forEach(item => {
          result.push.apply(result, item.split('-'))
        })
        return result
      },
      checkIP(list) {
        var result = true
        list.forEach(item => {
          if (!this.isValidIP(item)) {
            result = false
          }
        })
        return result
      },

      validate() {
        var isSubmit = true
        // this.$refs["startegies"].validate((valid) => {
        //     if (valid) {
        //         isSubmit = true
        //     } else {
        //         this.$refs.base.scrollTop = document.getElementById("startegies").offsetTop - 100
        //         this.$Message.error('请填写必填项');
        //     }
        // })
        // ------ 暂时注释
        // if(this.networkInfo.netType == '内网' || this.networkInfo.netType == 'CMNetDCI_vpn'){
        //   this.networkInfo.startegies.forEach((item, index) =>{
        //     this.networkInfo.startegies[index]['oriMapAddr'] = ''
        //     this.networkInfo.startegies[index]['targetMapAddr'] = ''
        //   })
        // }
        // var temp_stragies = this.networkInfo.startegies
        // temp_stragies.some((item, index) => {
        //   console.log("item ===> " ,item )
        //   if (item['direction'] == '') {
        //     isSubmit = false
        //     var s = '请填写第' + (index + 1) + '访问方向'
        //     this.$Message.error(s);
        //     return true
        //   }else if (item['oriAddr'] == '' ) {
        //     isSubmit = false
        //     var s = '请填写第' + (index + 1) + '行源地址IP'
        //     this.$Message.error(s);
        //     return true
        //   }else if (item['oriAddr'] != '' && !this.checkIP(this.splitIP(item['oriAddr']))) {
        //     isSubmit = false
        //     var s = '请正确填写第' + (index + 1) + '行源地址IP'
        //     this.$Message.error(s);
        //     return true
        //   }else if (item['targetAddr'] == '') {
        //     isSubmit = false
        //     var s = '请填写第' + (index + 1) + '行目的地址IP'
        //     this.$Message.error(s);
        //     return true
        //   }else if (item['targetAddr'] != '' && !this.checkIP(this.splitIP(item['targetAddr']))) {
        //     isSubmit = false
        //     var s = '请正确填写第' + (index + 1) + '行目的地址IP'
        //     this.$Message.error(s);
        //     return true
        //   }else if(this.networkInfo.netType != '内网' && this.networkInfo.netType != 'CMNetDCI_vpn'){
        //     if (item['oriMapAddr'] == '') {
        //       isSubmit = false
        //       var s = '请填写第' + (index + 1) + '行源地址对应的映射IP'
        //       this.$Message.error(s);
        //       return true
        //     }else if (item['oriMapAddr'] != '' && !this.checkIP(this.splitIP(item['oriMapAddr']))) {
        //       isSubmit = false
        //       var s = '请正确填写第' + (index + 1) + '行源地址对应的映射IP'
        //       this.$Message.error(s);
        //       return true
        //     }else if (item['targetMapAddr'] == '') {
        //       isSubmit = false
        //       var s = '请填写第' + (index + 1) + '行目的地址对应的映射IP'
        //       this.$Message.error(s);
        //       return true
        //     }else if (item['targetMapAddr'] != '' && !this.checkIP(this.splitIP(item['targetMapAddr']))) {
        //       isSubmit = false
        //       var s = '请正确填写第' + (index + 1) + '行目的地址对应的映射IP'
        //       this.$Message.error(s);
        //       return true
        //     }
        //   }
        // })
        // console.log("isSubmit ----->", isSubmit)
        // ------历史上传附件版本
        if(this.networkInfo.files == null || this.networkInfo.files.length == 0 ){
            isSubmit = false
            this.$Message.error('请上传网络策略申请附件');
        }
        return isSubmit
      },
      show_oriAddr_fun(index, key) {
        this.show_oriAddr = true;
        console.log('row----', this.networkInfo.startegies[index][key])
        this.INDEX = index;
        this.KEY = key;
        if (key == 'oriAddr') {
          this.TITLE = '源地址'
        }
        if (key == 'oriMapAddr') {
          this.TITLE = '源地址对应的映射IP'
        }
        if (key == 'targetAddr') {
          this.TITLE = '目的地址'
        }
        if (key == 'targetMapAddr') {
          this.TITLE = '目的地址对应的映射IP'
        }
      },
      getFiles() {
        return this.$refs.file.getFiles()
      },
      //格式化日期
      formatDate(value) {
        var date = new Date(value * 1000);
        var year = date.getFullYear();
        var month = this.padDate(date.getMonth() + 1);
        var day = this.padDate(date.getDate());
        return year + '-' + month + '-' + day;
      },
      padDate(value) {
        return value < 10 ? '0' + value : value;
      },
      addNetwork() {
        console.log('this.networkInfo', this.networkInfo)
        this.networkInfo.startegies.push()
      },
      addNetworkInfoList() {
        console.log('this.networkInfo', this.networkInfo)
        this.networkInfo.startegies.push({
          "appProtocol": "",
          "direction": "",
          "oriAddr": "",
          "oriMapAddr": "",
          "oriPortFrom": "",
          "oriPortTo": "",
          "purpose": "",

          "targetAddr": "",
          "targetMapAddr": "",
          "targetPortTo": "",
          "targetPortfrom": "",
          "tcpProtocol": "",
          "udpProtocol": ""
        })
      },
      deleteList(row, index) {
        console.log("deleteList", index)
        this.networkInfo.startegies.splice(index, 1)
      },
      changePage(page) {
        console.log('page', Object.prototype.toString.call(page) == '[object Number]')
        var that = this;
        if (page != undefined && page > 0 && page != null && Object.prototype.toString.call(page) ===
          '[object Number]') {
          that.page = page;
        } else {
          that.page = 1;
        }
        var param = {
          current: that.page,
          pageSize: that.pageSize,
          direction: this.search_param,
        }
        console.log('param:', param)
        var url = this.strategyyUrl + '/names';
        ajax.get({
          url: url,
          that: that,
          params: param,
          success: function(data) {
            console.log('changePage_data', data)
            that.startegies = data['records'];
            that.total_num = data['total'];
          }
        })
      },

      changePageSize(pageSize) {
        this.pageSize = pageSize;
        this.url_id = sessionStorage.getItem("url_id")
        if (this.url_id === "0") {
          this.get_all_strategy();
        } else if (this.url_id === "1") {
          var param = sessionStorage.getItem("param");
          this.search(param);
        }
      },


      get_all_strategy() {
        var that = this;
        var url = that.strategyyUrl + "/names";
        ajax.get({
          url: url,
          that: that,
          success: function(data) {
            console.log('get_all_strategy:', data)
            that.countSys = data
            sessionStorage.setItem("url_id", "0");
            that.changePage();
          }
        })
      },

      search(param) {
        if (param === '') {} else {
          this.changePage(1)
        }
      },

    },
    props: {
      ifedit: {},
      ishidden: {},
      severColumns: {},
      Papply: {},
      PfilesList: {},
    },
    //  computed:{
    //     tarPool(){
    //         return this.Papply.tarPool
    //     }
    // },
    watch: {
      Papply(newV, old) {
        console.log("newV--------->", newV)
        this.networkInfo = newV
      }
    }

  }
</script>
